<?php

namespace app\api\controller;

use app\api\model\User;
use app\common\controller\Api;
use think\Db;
use think\Request;

class Homework extends Api
{

    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->model = new \app\api\model\Homework();
    }

    // 布置作业列表
    public function index()
    {
        $uid          = $this->auth->id;
        $operation    = input('type/d');
        $cid          = input('cid/d');
        $start        = input('start/s');
        $where        = [];
        $exp          = [];
        $where['uid'] = $uid;
        if ($operation) {
            $where['operation'] = $operation;
        }
        if ($cid) {
            $where['cid'] = $cid;
            //$exp[] = ['exp',Db::raw('FIND_IN_SET('.$cid.',cidarr)')];
        }
        if ($start) {
            $where['deadlinetime'] = ['between', [$start, date('Y-m-d H:i:s')]];
        }
        $page       = input('page/d') && is_numeric(input('page/d')) ? input('page/d') : 1;
        $pageSize   = input('pageSize/d') && is_numeric(input('pageSize/d')) ? input('pageSize/d') : 10;
        $list       = $this->model->where($where)->where($exp)->page($page, $pageSize)->select();
        $productarr = [
            1 => 'hear_say',
            2 => 'listening',
            3 => 'repeat',
            4 => 'writing',
            5 => 'soundmark',
            6 => 'model',
            7 => 'new_concept',
            8 => '_black_plum',
        ];
        foreach ($list as &$vv) {
            $gradeid     = Db::name('grade_class')->where('id', $vv['cid'])->value('grade_id');
            $vv['cname'] = Db::name('grade')->where('grade', $gradeid)->value('gradeName') . Db::name('grade_class')->where('id', $vv['cid'])->value('name');
            $vv['pname'] = Db::name($productarr[$vv['ptype']] . '_products')->where('productId', $vv['pid'])->value('productName');
            $vv['isend'] = 0;
            if ($vv['deadlinetime'] <= date('Y-m-d H:i:s')) {
                $vv['isend'] = 1;
            }

            $vv['shitiarr'] = [];
            if ($vv['ridjson']) {
                $ridarr   = json_decode($vv['ridjson'], true);
                $shitiarr = [];
                foreach ($ridarr as $vs) {
                    $ds             = [];
                    $ds['pid']      = $vs['pid'];
                    $ds['tid']      = $vs['tid'];
                    $ds['tname']    = Db::name($productarr[$vv['ptype']] . '_resources')->where('versionId', $vs['tid'])->value('resourceName');
                    $donum          = Db::name('reciting_mission')->where(['mission_id' => $vv['id'], 'source_id' => $vs['tid']])->group('user_id')->count();
                    $ds['donum']    = $donum;
                    $ds['unum']     = count(explode(',', $vv['uidarr']));
                    $ds['islayout'] = $this->model->where(['id' => ['<>', $vv['id']], 'uid' => $uid, 'ridjson' => ['like', '%' . $vs['tid'] . '%'], 'status' => 1])->count() ? 1 : 0;
                    $shitiarr[]     = $ds;
                }
                $vv['shitiarr'] = $shitiarr;
            }
            $lexp = [];
            //$lexp[] = ['exp',Db::raw('FIND_IN_SET('.$vv['rid'].',ridarr)')];
            //$layout = $this->model->where($lexp)->count();
            //$vv['layout'] = $layout;
            //$vv['scoringrate'] = '0%';
            //$vv['usenum'] = 1;
        }
        unset($vv);
        $this->success('请求成功', $list);
    }

    // 发布作业
    public function add()
    {
        $data = input();
        if (!isset($data['cidjson']) && !$data['cidjson']) {
            $this->error(__('Invalid parameters'));
        }
        $rarr            = is_array($data['ridjson']) ? $data['ridjson'] : json_decode(htmlspecialchars_decode($data['ridjson']), true);
        $data['ridjson'] = is_array($data['ridjson']) ? json_encode($data['ridjson']) : htmlspecialchars_decode($data['ridjson']);
        $ridarr          = [];
        foreach ($rarr as $k => $vv) {
            $ridarr[$k] = $vv['tid'];
        }
        $data['ridarr']     = implode(',', $ridarr);
        $carr               = is_array($data['cidjson']) ? $data['cidjson'] : json_decode(htmlspecialchars_decode($data['cidjson']), true);
        $data['createtime'] = date('Y-m-d H:i:s');
        $data['startTime']  = isset($data['startTime']) && $data['startTime'] ? $data['startTime'] : date('Y-m-d H:i:s');
        $sd                 = $data;
        unset($sd['cidjson']);
        $sd['uid'] = $this->auth->id;
        $userModel = new \app\admin\model\User();
        foreach ($carr as $vs) {
            $sd['cid'] = $vs['id'];

            if ($vs['uid']) {
                $sd['uidarr'] = implode(',', $vs['uid']);
            } else {
                $ids          = $userModel->where('class_id', $vs['id'])->column('id');
                $sd['uidarr'] = implode(',', $ids);
            }
            $result = $this->model->save($sd);
        }

        if ($result) {
            //发布成功将试题缓存数据清空
            $userModel->where('id', $this->auth->id)->update(['question_text' => null]);
            $this->success('发布成功');
        } else {
            $this->success('发布失败');
        }

    }

    // 修改布置作业
    public function edit()
    {
        $data   = input();
        $result = $this->model->save($data, ['id' => $data['id']]);
        if ($result) {
            $this->success('修改成功');
        } else {
            $this->success('修改失败');
        }

    }

    // 布置作业详情
    public function detail()
    {
        $id     = input('id/d');
        $detail = $this->model->where(['id' => $id])->find();

        $this->success('请求成功', $detail);
    }

    //获取作业列表(学生端)v
    public function getStudentHomeworkList()
    {
        $params         = input();
        $params['uid']  = $this->auth->id;
        if (!$params['uid']) {
            $this->success('请先登录', []);
        }

        $page     = input('page/d') && is_numeric(input('page/d')) ? input('page/d') : 1;
        $pageSize = input('pageSize/d') && is_numeric(input('pageSize/d')) ? input('pageSize/d') : 10;

        //class 班级
        $userInfo = Db::table('fa_user')->where(['id' => $params['uid'], 'type' => 2])->find();

        $map = "((cid = '{$userInfo['class_id']}' AND uidarr IS NULL) OR (cid = '{$userInfo['class_id']}' AND uidarr LIKE'%{$params['uid']}%')) AND status = 1 AND operation = {$params['operation']}";

        $rel        = Db::table('fa_homework')->where($map)->order('createtime desc')
            //->where('id','46')
            ->page($page, $pageSize)->select();
        $productarr = [
            1 => 'hear_say',
            2 => 'listening',
            3 => 'repeat',
            4 => 'writing',
            5 => 'soundmark',
            6 => 'model',
            7 => 'new_concept',
            8 => 'black_plum',
            9 => 'textbook_synchronization',
        ];
        foreach ($rel as &$v) {
            $v['rid_arr'] = json_decode($v['ridjson'], true);

            $tabProName = 'fa_' . $productarr[$v['ptype']] . '_products';//教材表
            $tabResName = 'fa_' . $productarr[$v['ptype']] . '_resources'; //考试资源表
            foreach ($v['rid_arr'] as $k => &$vv) {
                if($v['ptype'] == 9){
                    $tabProRel = Db::table($tabProName)->where(['versionId' => $vv['pid']])->find();
                    $tabResRel = Db::table($tabResName)->where(['versionId' => $vv['tid']])->find();
                }else{
                    $tabProRel = Db::table($tabProName)->where(['productId' => $vv['pid']])->find();
                    $tabResRel = Db::table($tabResName)->where(['versionId' => $vv['tid']])->find();
                }

                //作业考试回答
                if ($params['operation'] == 1) {
                    $mission_type = 0;
                } elseif ($params['operation'] == 2) {
                    $mission_type = 3;
                } else {
                    $mission_type = 0;
                }

                //if($tabResRel){
                    $missionRel = Db::table('fa_reciting_mission')
                        ->where(['mission_id' => $v['id'],
                                'user_id' => $params['uid']
                                //'source_id' => $tabResRel['versionId'],
                                //'mission_type' => $mission_type
                        ])->find();
                //}
                if ($v['ptype'] == 9) {
                    $vv['resourceUrl'] = fileurl($tabResRel['resourceUrl'].'/resource/resource.json',true);
                    $vv['productName']  = !empty($tabProRel['versionName']) ? $tabProRel['versionName'] : null; //教材 名称 

                }else{

                   $vv['productName']  = !empty($tabProRel['productName']) ? $tabProRel['productName'] : null; //教材 名称 
                   $vv['resourceUrl'] = fileurl($tabResRel['gunzipResPath'],true);
                   
                }

                $vv['resourceName'] = !empty($tabResRel['resourceName']) ? $tabResRel['resourceName'] : NULL; //资源练习 名称
                $vv['resourceType']  = !empty($tabResRel['resourceType']) ? $tabResRel['resourceType'] : null; //类型 
                $vv['moduleName']  = !empty($tabResRel['moduleName']) ? $tabResRel['moduleName'] : null; //类型 
                $vv['versionId']    = !empty($tabResRel['versionId']) ? $tabResRel['versionId'] : NULL; //考试资源详情ID

                //待完善
                $vv['teacher_talk_num'] = 1;//老师要求读次数
                $vv['student_talk_num'] = !empty($missionRel['is_done']) == 1 ? 1 : 0;//自己已读次数

                $vv['exam_fraction']         = !empty($missionRel['full_score']) ? $missionRel['full_score'] : 100;//考试总分数

                $vv['student_exam_num']      = !empty($missionRel['is_done']) == 1 ? 2 : 1;//学生作业状态 1：未完成 2：已完成
                $vv['student_exam_fraction'] = !empty($missionRel['score']) ? $missionRel['score'] : 0;//学生考试分数
                $vv['homework_percentage']   = round($vv['student_exam_fraction'] / $vv['exam_fraction'] * 100) . '%';//作业百分比

            }
        }
        $this->success('请求成功', $rel);
    }

    //获取作业列表章节数据统计(学生端)
    public function getStudentHomeworkListEveryStatistics()
    {
        $params        = input();
        $params['uid'] = $this->auth->id;
        if (!$params['uid']) {
            $this->success('请先登录', []);
        }
        //试卷详情
        $missionRel = Db::table('fa_reciting_mission')
           ->where(['mission_id' => $params['homeworkid'],
                'user_id' => $params['uid'],
                'source_id' => $params['versionId'],
                //'mission_type' => $params['mission_type']
            ])
           // ->where('id','221')
            ->find();
        if (!$missionRel) {
            $this->success('请先完成提交作业试题！！！');
        }

        //获取学生详情
        $userInfo = Db::table('fa_user')->where(['id' => $params['uid'], 'type' => 2])->find();
        //获取所有学生
        $userInfoArr = Db::table('fa_user')->where(['class_id' => $userInfo['class_id'], 'type' => 2])->select();

        //查询所有学生的试卷详情
        $uidArr        = array_column($userInfoArr, 'id');
        $missionRelArr = Db::table('fa_reciting_mission')
            ->where(['mission_id' => $params['homeworkid'], 'user_id' => ['in', $uidArr], 'source_id' => $params['versionId'],
                //'mission_type' => $params['mission_type']
            ])
            ->select();

        //所有分数
        $missionRelScoreArr = array_column($missionRelArr, 'score');
        //最大分数
        $missionRelScoreMaxPos = array_search(max($missionRelScoreArr), $missionRelScoreArr);
        $missionRelScoreMax    = $missionRelScoreArr[$missionRelScoreMaxPos];

        //平均分
        $missionRelScorePj = round(array_sum($missionRelScoreArr) / count($missionRelScoreArr), 2);

        $missionRelDoneArr = [];

        $score_1 = $score_2 = $score_3 = $score_4 = $score_5 = $score_6 = $score_7 = [];
        foreach ($missionRelArr as $v) {
            if ($v['is_done'] == 1) {//所有完成的人数
                $missionRelDoneArr[] = $v;
            }

            $score = $v['score'] / $v['full_score'];
            if ($score >= 0 && $score < 0.2) {
                $score_1[] = $score;
            }
            if ($score >= 0.2 && $score < 0.4) {
                $score_2[] = $score;
            }
            if ($score >= 0.4 && $score < 0.6) {
                $score_3[] = $score;
            }
            if ($score >= 0.6 && $score < 0.7) {
                $score_4[] = $score;
            }
            if ($score >= 0.7 && $score < 0.8) {
                $score_5[] = $score;
            }
            if ($score >= 0.8 && $score < 0.9) {
                $score_6[] = $score;
            }
            if ($score >= 0.9) {
                $score_7[] = $score;
            }
        }

        $rel = [
            'homework_resources_name' => $missionRel['title'], //名称
            'score'                   => $missionRel['score'],//得分
            'score_rate'              => round($missionRel['score'] / $missionRel['full_score'] * 100) . '%',//得分率
            'score_class_high'        => $missionRelScoreMax . '/' . $missionRel['full_score'],//班级最高得分
            'score_class_average'     => $missionRelScorePj . '/' . $missionRel['full_score'],//班级平均得分
            'complete_num'            => count($missionRelDoneArr),//完成人数

            'score_arr'  => [ //分数段分析
                              '0-20%'   => count($score_1),
                              '20-40%'  => count($score_2),
                              '40-60%'  => count($score_3),
                              '60-70%'  => count($score_4),
                              '70-80%'  => count($score_5),
                              '80-90%'  => count($score_6),
                              '90-100%' => count($score_7),
            ],
            'full_score' => $missionRel['full_score'],//总分
            'use_time'   => $missionRel['use_time'],//作答用时
            'remark'     => '',//备注
            'json' => json_decode(file_get_contents($missionRel['json']), true),
            'answer_score_json' => json_decode($missionRel['answer_score_json']),
        ];
        $this->success('请求成功', $rel);
    }
}